import React, { useState, useRef } from 'react';
import { format } from '@/utils/datetime';
import { renderNumber } from '@/utils/common';
import ListReport from '@/components/report/ReportTable';
import DataTable from '@/components/base/DataTable';
import DataEdit from '@/components/base/DataEdit';
import PageHeader from '@/components/page/PageHeader';
import { useModel } from 'umi';
import { saveDivi } from '@/services/AccountDivi';
import { Row, Col, Card, Table, Space, Button, message, Modal, Badge, List } from 'antd';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import _ from 'lodash';
// 属性类型
type PropField = {
  /** 搜索认定账户报表配置文件的名称 */
  reportName: string;
  /** 认定报表主键的名称 */
  keyColName: string;
  /** 认定类型 */
  diviType: API.DiviType;
  /** 认定card显示的标题 */
  titleColNames: string[];
};
const DividePage: React.FC<PropField> = (props) => {
  const [selRows, setSelRows] = useState<Record<string, any>[]>([]);
  const [selKeys, setSelKeys] = useState<React.Key[]>([]);
  const [curSearchVals, setCurSearchVals] = useState<Record<string, any>>({});
  const [doingDivis, setDoingDivis] = useState<Record<string, any>[]>([]);
  const tableRef = useRef<API.TableAction>();
  const diviColumns: API.Column[] = [
    { title: '员工号', dataIndex: 'EMNO', key: 'EMNO', width: 70, dispaly: true, fixed: false },
    {
      title: '员工名',
      width: 70,
      dataIndex: 'EMNM',
      key: 'EMNM',
      dispaly: true,
      fixed: false,
    },
    {
      title: '所属部门',
      width: 90,
      dataIndex: 'DPNM',
      key: 'DPNM',
      dispaly: true,
      ellipsis: true,
    },
    {
      title: props.diviType === 'CmBizFee' ? '分成金额(元)' : '比例(%)',
      width: 90,
      dataIndex: 'DSVL',
      key: 'DSVL',
      dispaly: true,
      render: (data) => renderNumber(props.diviType === 'CmBizFee' ? '.2f' : '.2f%', data),
    },
  ];
  if (props.diviType !== 'CmBizFee') {
    diviColumns.push({
      title: '分户日期',
      width: 80,
      key: 'DSDT',
      dataIndex: 'DSDT',
      render: (data) => format(data, 'yyyyMMdd'),
      dispaly: true,
    });
    diviColumns.push({
      title: '终止日期',
      width: 80,
      key: 'WODT',
      dataIndex: 'WODT',
      render: (data) => format(data, 'yyyyMMdd'),
      dispaly: true,
    });
  }
  if (props.diviType === 'Comp') {
    diviColumns.push({
      title: '申请日期',
      width: 80,
      key: 'SQDT',
      dataIndex: 'SQDT',
      render: (data) => format(data, 'yyyyMMdd'),
      dispaly: true,
    });
  }
  const diviColumns2: API.Column[] = [
    { title: '员工编号', dataIndex: 'EMNO', key: 'EMNO', width: 80 },
    {
      title: '员工名称',
      width: 80,
      dataIndex: 'EMNM',
      key: 'EMNM',
    },
    {
      title: '所属部门',
      width: 80,
      dataIndex: 'DPNM',
      key: 'DPNM',
    },
    {
      title: props.diviType === 'CmBizFee' ? '分成金额(元)' : '分成比例(%)',
      width: 90,
      dataIndex: 'DSVL',
      key: 'DSVL',
    },
  ];
  const editDiviControls: API.Control[] = [
    {
      name: 'EMID',
      type: 'search',
      label: '员工',
      width: 100,
      fetch: {
        tableName: 'User',
        searchColumns: ['No', 'Name'],
        optionTpl: 'Name',
        valueTpl: 'ID',
        isDao: true,
        onSelect: async (vals) => setCurSearchVals(vals as Record<string, any>),
      },
      placeholder: '请输入工号或者姓名',
      rules: [{ required: true, message: '必须搜索和选择员工' }],
    },
    {
      name: 'DSVL',
      type: 'number',
      label: props.diviType === 'CmBizFee' ? '金额(元)' : '占比(%)',
      width: 80,
      rules: [{ required: true, message: '必须填写占比' }],
    },
  ];
  const addDivi = async (values: Record<string, any>) => {
    const emid = Number(values.EMID);
    const dsvl = Number(values.DSVL);
    if (doingDivis.findIndex((d) => d.EMID === emid) !== -1) {
      message.error(`认定员工${curSearchVals.EMNM}已存在，不能重复添加`);
      return;
    }
    let sum = dsvl;
    doingDivis.forEach((d) => {
      sum += d.DSVL;
    });
    if (props.diviType === 'CmBizFee') {
      if (sum - (selRows[0].ZSJE as number) > 0.01) {
        message.error(`金额超过总金额:${selRows[0].ZSJE}，不能添加`);
        return;
      }
    } else {
      if (sum > 100) {
        message.error(`占比超过100%，不能添加`);
        return;
      }
    }
    const divi = {
      EMID: emid,
      EMNO: curSearchVals.No,
      EMNM: curSearchVals.Name,
      DPNM: curSearchVals.Organization.Name,
      DSVL: dsvl,
    };
    const newDivis = [...doingDivis, divi];
    setDoingDivis(newDivis);
  };
  const getTitle = (row: Record<string, any>) => {
    const titles: JSX.Element[] = [];
    props.titleColNames.forEach((t) => {
      titles.push(<span>{row[t]}</span>);
    });
    return <Space key={row[props.keyColName]}>{titles}</Space>;
  };
  const getTitles = () => {
    if (_.isEmpty(selRows) || _.isEmpty(props.titleColNames)) {
      return [<div key="1">确认点击确定，退出点击取消</div>];
    }
    return selRows.map((r) => getTitle(r));
  };
  const submitDivi = async (values: Record<string, any>) => {
    if (_.isEmpty(selRows)) {
      message.error(`请选择要认定的${props.diviType === 'CmBizFee' ? '中收交易' : '账户'}`);
      return;
    }
    const keys: number[] = [];
    selRows.forEach((row) => {
      keys.push(Number(row[props.keyColName]));
    });
    const divis: Record<number, number> = {};
    let sum = 0;
    doingDivis.forEach((d) => {
      divis[d.EMID] = props.diviType === 'CmBizFee' ? d.DSVL : d.DSVL / 100;
      sum += Number(d.DSVL);
    });
    if (props.diviType === 'CmBizFee') {
      if (Math.abs(sum - (selRows[0].ZSJE as number)) > 0.01) {
        message.error(`金额之和必须等于总金额:${selRows[0].ZSJE}`);
        return;
      }
    } else {
      if (Math.abs(sum - 100) > 0.1) {
        message.error('占比之和必须等于100%');
        return;
      }
    }
    Modal.confirm({
      title: (
        <div key="1">
          你确认要保存选中的
          <Badge count={keys.length} overflowCount={100} style={{ backgroundColor: '#87d068' }} />
          {props.diviType === 'CmBizFee' ? '中收交易' : '账户'}认定关系吗？
        </div>
      ),
      icon: <ExclamationCircleOutlined />,
      width: 800,
      content: (
        <div style={{ maxHeight: 600, overflow: 'auto' }}>
          <List
            size="small"
            dataSource={getTitles()}
            renderItem={(item) => <List.Item>{item}</List.Item>}
          />
        </div>
      ),
      onOk: () => {
        saveDivi(props.diviType, keys, format(values.DSDT, 'yyyy-MM-dd'), divis)
          .then(function (data) {
            if (data === 'OK') {
              if (tableRef.current) {
                tableRef.current.reload();
              }
              setDoingDivis([]);
            }
          })
          .catch(function (ex) {
            console.error('保存认定关系', props.diviType, '出错', ex);
          });
      },
      okText: '确认',
      cancelText: '取消',
    });
  };
  let daoName: string = '';
  if (props.diviType === 'Comp') {
    daoName = 'CompAccoDivi';
  } else if (props.diviType === 'Indi') {
    daoName = 'IndiAccoDivi';
  } else if (props.diviType === 'IndiLoan') {
    daoName = 'IndiLoanDivi';
  } else if (props.diviType === 'CmBizFee') {
    daoName = 'CmBizFeeDivi';
  }
  const seeks: API.WhereCause[] = [
    {
      WhereItems: [
        {
          FieldName: props.keyColName,
          Operator: '=',
          FieldValues:
            selRows.length === 0 ? '-1' : String(selRows[selRows.length - 1][props.keyColName]),
        },
      ],
      RelationSign: 'AND',
    },
  ];
  const titles: JSX.Element[] = [];
  let initDsdt: any = undefined;
  if (!_.isEmpty(selRows) && !_.isEmpty(props.titleColNames)) {
    const row = selRows[selRows.length - 1];
    if (props.diviType === 'CmBizFee') {
      initDsdt = row.DATA_DT;
    } else {
      initDsdt = row.VLDT;
    }
    props.titleColNames.forEach((t) => {
      titles.push(<span>{row[t]}</span>);
    });
  }
  const { bodyHeight, permTypes } = useModel('sysInfo', (ret) => ({
    bodyHeight: ret.bodyHeight,
    permTypes: ret.getCurPermTypes(),
  }));
  const canEdit =
    permTypes &&
    permTypes.indexOf('4') !== -1 &&
    permTypes &&
    permTypes.indexOf('6') !== -1 &&
    permTypes &&
    permTypes.indexOf('7') !== -1;
  const diviHeigth = canEdit ? bodyHeight / 2 : bodyHeight;
  return (
    <PageHeader>
      <Row>
        <Col span={_.isEmpty(selRows) || _.isEmpty(props.titleColNames) ? 24 : 15}>
          <ListReport
            reportName={props.reportName}
            onSelectChange={async (_keys: React.Key[], rows: object[]) => {
              setSelRows(rows);
            }}
            multiSelect={props.diviType === 'CmBizFee' || !canEdit ? false : true}
            canExport={false}
            canClearFilter={false}
            canSelectItems={false}
          />
        </Col>
        <Col
          span={9}
          style={{
            display: _.isEmpty(selRows) || _.isEmpty(props.titleColNames) ? 'none' : 'block',
          }}
        >
          <Card
            title={
              _.isEmpty(selRows) || _.isEmpty(props.titleColNames)
                ? '查看认定关系'
                : getTitle(selRows[selRows.length - 1])
            }
            bodyStyle={{ padding: 0, height: diviHeigth - 165 }}
          >
            <DataTable
              daoName={daoName}
              height={diviHeigth - 165}
              columns={diviColumns}
              pageSize={10}
              actionRef={tableRef}
              canClearFilter={false}
              canExport={false}
              canPage={false}
              canPageSize={false}
              canSelectItems={false}
              seeks={seeks}
              canSelectRow={false}
              initSorter={{
                FieldName: props.diviType === 'CmBizFee' ? 'JLID' : 'DSDT',
                Direction: 'DESC',
              }}
            />
          </Card>
          {canEdit ? (
            <Card title="认定给员工" style={{ marginTop: 10 }} bodyStyle={{ padding: 0 }}>
              <div style={{ marginTop: 5, marginBottom: 5 }}>
                <DataEdit
                  key="edit"
                  controls={editDiviControls}
                  showType="inner"
                  layout="inline"
                  grid={false}
                  autoFocusFirstInput={false}
                  onSumit={addDivi}
                  renderButtons={(p) => {
                    return [
                      <Space key="extraButtons">
                        <Button type="primary" key="new" onClick={() => p.form?.submit?.()}>
                          添加
                        </Button>
                        <Button
                          type="primary"
                          key="del"
                          onClick={() => {
                            if (selKeys.length === 0) {
                              message.info('请在下方列表中选择要删除的认定关系');
                              return;
                            }
                            const newDivis: Record<string, any>[] = [];
                            doingDivis.forEach((d) => {
                              if (d.EMID !== selKeys[0]) {
                                newDivis.push(d);
                              }
                            });
                            setDoingDivis(newDivis);
                          }}
                        >
                          删除
                        </Button>
                      </Space>,
                    ];
                  }}
                />
              </div>
              <Table
                key="list"
                columns={diviColumns2}
                dataSource={doingDivis}
                bordered={true}
                size="middle"
                rowKey={(row) => row.EMID}
                rowSelection={{
                  selectedRowKeys: selKeys,
                  onChange: (keys) => setSelKeys(keys),
                  type: 'radio',
                }}
              />
              <div style={{ marginTop: 5, marginBottom: 5 }}>
                <DataEdit
                  key="submit"
                  controls={[
                    {
                      name: 'DSDT',
                      type: 'date',
                      dataType: 'date',
                      label: '认定日期',
                      rules: [{ required: true, message: '必须选择认定日期' }],
                    },
                  ]}
                  showType="inner"
                  layout="inline"
                  grid={false}
                  initVals={{ DSDT: initDsdt }}
                  autoFocusFirstInput={false}
                  onSumit={submitDivi}
                  renderButtons={(p) => {
                    return [
                      <Space key="extraButtons">
                        <Button type="primary" key="new" onClick={() => p.form?.submit?.()}>
                          提交
                        </Button>
                      </Space>,
                    ];
                  }}
                />
              </div>
            </Card>
          ) : null}
        </Col>
      </Row>
    </PageHeader>
  );
};
export default DividePage;
